package com.kt.delivery.service;


import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kt.delivery.domain.R;
import com.kt.delivery.domain.User;
import com.kt.delivery.domain.vo.LoginUser;
import com.kt.delivery.domain.vo.WeChatSessionModel;
import com.kt.delivery.exception.ApiException;
import com.kt.delivery.mapper.UserMapper;
import com.kt.delivery.utils.JWTUtil;
import com.kt.delivery.utils.WechatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class LoginUserService {

    private final UserMapper userMapper;

    private final WechatUtil wechatUtil;

    private final JWTUtil jwtUtil;

    private final RedisTemplate<String,Object> redisTemplate;


    /**
     * 返回的用户信息
     * @param code code
     * @return 结果
     */
    public R<LoginUser> checkLogin(String code) throws Exception {

        // 通过前端传的code调用微信小程序登陆地址
        String body = wechatUtil.getSessionKeyOpenid(code);


        // 把body转成weChatSessionModel类
        WeChatSessionModel weChatSessionModel = JSONObject.parseObject(body, WeChatSessionModel.class);

        log.info(weChatSessionModel.toString());

        // 判断是否获取到openid
        if (weChatSessionModel.getOpenid() == null){
            log.info("openid错误:{}"+weChatSessionModel.getErrMsg());
            throw new ApiException("code码已消费","300");
        }

        // 判断用户是否存在
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getOpenId,weChatSessionModel.getOpenid());
        User user = userMapper.selectOne(userLambdaQueryWrapper);

        if (user == null) {
            User userOne = new User();
            userOne.setIfTaking(0);
            userOne.setOpenId(weChatSessionModel.getOpenid());
            userOne.setJm(BigDecimal.valueOf(0));
            userOne.setCreateTime(new Date());

            // 新增用户信息
            userMapper.insert(userOne);


            // 创建token
            String token = jwtUtil.createToken(userOne.getId());

            // 存到redis中
            redisTemplate.opsForValue().set("token:"+token,userOne, 7,TimeUnit.DAYS);

            // 封装loginUser返回
             return R.ok(returnLoginUser(userOne,token));

        }else {
            String token = jwtUtil.createToken(user.getId());
            // 存到redis中
            redisTemplate.opsForValue().set("token:"+token,user, 7,TimeUnit.DAYS);
            return R.ok(returnLoginUser(user,token));
        }


    }

    /**
     * 封装返回用户信息
     * @param user 用户信息
     * @param token token
     * @return 结果
     */
    public LoginUser returnLoginUser(User user,String token){
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user,loginUser);
        loginUser.setToken(token);
        return loginUser;
    }
}
